﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.UI;
using System.Xml;
using System.Xml.Linq;
using FlickrXplorer.Web.ViewData;
using FlickrXplorer.Web.ViewData;

namespace FlickrXplorer.Web.Utilities
{
    /// <summary>
    /// contains HtmlHelper related extensions
    /// </summary>
    public static class HtmlExtensions
    {
        static System.Text.RegularExpressions.Regex _urlPattern = new System.Text.RegularExpressions.Regex("(href=\").[^\"]*.(\")", System.Text.RegularExpressions.RegexOptions.Compiled);

        public static string ToInputCheckedAttribute(this bool isChecked)
        {
            return isChecked ? "checked" : "";
        }

        public static string ActionUrl(this HtmlHelper html, string controller, string actionName, object values)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("/" + controller + "/" + actionName);

            if (values != null)
            {

                PropertyInfo[] infos = values.GetType().GetProperties();

                if (infos.Length > 0)
                {
                    builder.Append("?");
                }

                foreach (var propertyInfo in infos)
                {
                    builder.Append(propertyInfo.Name + "=" + propertyInfo.GetValue(values, null) + "&");
                }

                if (builder.Length > 0)
                {
                    builder.Replace("&", string.Empty, builder.Length - 1, 1);
                }

            }
            return builder.ToString();
        }
        /// <summary>
        /// this is build the form url base on the current url.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="paramToExclude"></param>
        /// <returns></returns>
        public static string RenderRequiredFormPostElements(this HtmlHelper htmlHelper, string paramToExclude)
        {
            string url = HttpContext.Current.Request.Path;

            StringBuilder builder = new StringBuilder();
            NameValueCollection queries = HttpContext.Current.Request.QueryString;

            foreach (string name in queries.AllKeys)
            {
                if (string.Compare(name, paramToExclude, true) == 0)
                {
                    //skip
                }
                else
                {
                    builder.Append(htmlHelper.Hidden(name, new { value = queries[name] }));
                }
            }
            return builder.ToString();
        }

        public static string BuildUrlWithAppPath(this Page page, string path)
        {
            string appPath = VirtualPathUtility.RemoveTrailingSlash(page.Request.ApplicationPath);

            if (appPath == "/")
            {
                // do nothing
            }
            else
            {
                path = appPath + path;
            }
            return path;
        }


        public static BookmarkCollection LoadBookmark(string path)
        {
            XDocument document = XDocument.Load(XmlReader.Create(new StreamReader(path)));

            var query = from bookmark in document.Descendants("bookmark")
                        select new Bookmark
                        {
                            Title = bookmark.Attribute("title").Value,
                            Url = bookmark.Attribute("url").Value,
                            Name = bookmark.Attribute("name").Value,
                            Ext = bookmark.Attribute("ext").Value
                        };


            BookmarkCollection bookmarks = new BookmarkCollection();
            bookmarks.AddRange(query.AsEnumerable<Bookmark>());
            return bookmarks;
        }

        /// <summary>
        /// get the cookie previously stored in a cookie.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>full url of the stored path</returns>
        public static string GetStoredUrl(this HttpRequestBase request)
        {
            HttpCookie cookie = request.Cookies["url"];
            if (cookie != null)
            {
                return cookie.Value;
            }
            return string.Empty;
        }

        public static IDisposable JForm(this HtmlHelper helper, string action, string method, JOptions options)
        {
            return new JQueryForm(helper, action, method, options, null);
        }

        public static IDisposable JForm(this HtmlHelper helper, string action, string method, JOptions options, object htmlAttribtues)
        {
            return new JQueryForm(helper, action, method, options, htmlAttribtues);
        }

        public static string AjaxActionLink(this HtmlHelper helper, string linkText, string action, string controller, JOptions options, object routeValues)
        {
            TagBuilder tagBuilder = new TagBuilder("a");

            string jsFormat = "javascript:renderContent('" + options.TargetPanelId +  "', '"+ options.WaitPanelId +"', '/{0}/{1}', {2});";

            StringBuilder builder = new StringBuilder();

            PropertyInfo[] infos = routeValues.GetType().GetProperties();

            if (infos.Length > 0)
            {
                builder.Append("{");
            }

            foreach (var propertyInfo in infos)
            {
                builder.Append(propertyInfo.Name + ":" + propertyInfo.GetValue(routeValues, null) + ",");
            }

            builder.Replace("True", "1");
            builder.Replace("False", "0");

            if (builder.Length > 0)
            {
                builder.Replace(",", string.Empty, builder.Length - 1, 1);
            }

            builder.Append("}");

            tagBuilder.MergeAttribute("href", string.Format(jsFormat, controller, action, builder.ToString()));

            return tagBuilder.ToString(TagRenderMode.StartTag) + linkText + "</a>";
        }

    }
}
